﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace TileMap
{
    class MapTileSave : IMapTileFilter
    {
        public int RowCount { get; set; }

        public int ColumnCount { get; set; }

        public int Row { get; set; }

        public int Column { get; set; }

        public int FilterRow { get; set; }

        public int FilterColumn { get; set; }

        public int MaxRowInChildren { get; set; }

        public int MinColumnInChildren { get; set; }

        public string SaveFileName { get; set; }

        private List<MapCellDown> mapCellDowns = new List<MapCellDown>();

        private Image MapImage;

        public void AddCell(MapCellDown mapCell)
        {
            mapCellDowns.Add(mapCell);
        }

        public void GetImageAsync(IMapTileFilter filter)
        {
            MapImage = new Bitmap(ColumnCount * 256, RowCount * 256, PixelFormat.Format24bppRgb);

            Parallel.ForEach(mapCellDowns,
                new ParallelOptions()
                {
                    MaxDegreeOfParallelism = 8
                },
                x => x.GetImageAsync(this).Wait());

            // 并行线程过多
            //Task.WaitAll(mapCellDowns.Select(x => Task.Factory.StartNew(
            //    () => { x.GetImageAsync(this).Wait(); })).ToArray());

            //使用await 只能一个一个的计算
            //foreach (var item in mapCellDowns)
            //{
            //    await item.GetImageAsync(this);
            //}

            if (!string.IsNullOrEmpty(SaveFileName))
            {
                MapImage.Save(SaveFileName, ImageFormat.Jpeg);
            }

            filter?.Filter(MapImage, FilterRow, FilterColumn);

            MapImage.Dispose();
            MapImage = null;
        }

        public void Filter(Image image, int row, int column)
        {
            if (MapImage != null && image != null)
            {
                lock (this)
                {
                    using (var g = Graphics.FromImage(MapImage))
                    {
                        g.DrawImageUnscaled(image,
                            (column - MinColumnInChildren) * 256,
                            (MaxRowInChildren - row) * 256);
                    }
                }
            }
        }
    }
}
